package com.hzy.fivepalace.common.notify;

import java.util.ArrayList;
import java.util.List;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.binarywang.wx.miniapp.api.WxMaService;
import org.springframework.beans.factory.annotation.Value;

/**
 * 微信模版消息通知
 */
public class WxTemplateSender {
    private final Log logger = LogFactory.getLog(WxTemplateSender.class);

    @Autowired
    private WxMaService wxMaService;

    @Value("${hzy.wx.app-id}")
    private String appId;



    /**
     * 发送微信消息(模板消息),不带跳转
     *
     * @param touser    用户 OpenID
     * @param templatId 模板消息ID
     * @param parms     详细内容
     */
    public void sendWechatMsg(String touser, String templatId, String[] parms, NotifyType notifyType) {
        sendMsg(touser, templatId, parms, "", notifyType);
    }

    /**
     * 发送微信消息(模板消息),带跳转
     *
     * @param touser    用户 OpenID
     * @param templatId 模板消息ID
     * @param parms     详细内容
     * @param page      跳转页面
     */
    public void sendWechatMsg(String touser, String templatId, String[] parms, String page, NotifyType notifyType) {
        sendMsg(touser, templatId, parms, page, notifyType);
    }

    private void sendMsg(String touser, String templatId, String[] parms, String page, NotifyType notifyType) {
        WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
        subscribeMessage.setToUser(touser);
        subscribeMessage.setTemplateId(templatId);
        subscribeMessage.setToUser(touser);
        subscribeMessage.setPage(page);
        subscribeMessage.setData(createMsgData(parms, notifyType));
        //小程序跳转类型为体验版
        subscribeMessage.setMiniprogramState(WxMaConstants.MiniprogramState.FORMAL);
        try {
            wxMaService.switchoverTo(appId).getMsgService().sendSubscribeMsg(subscribeMessage);
        } catch (Exception e) {
        }
    }


    private List<WxMaSubscribeMessage.Data> createMsgData(String[] parms, NotifyType notifyType) {
        List<WxMaSubscribeMessage.Data> dataList = new ArrayList<WxMaSubscribeMessage.Data>();

        if (notifyType.getType().equals(NotifyType.SHIP.getType())) {//发货提醒模板
            dataList.add(new WxMaSubscribeMessage.Data("character_string1", parms[0]));
            dataList.add(new WxMaSubscribeMessage.Data("name2", parms[1]));
            dataList.add(new WxMaSubscribeMessage.Data("character_string3", parms[2]));
            dataList.add(new WxMaSubscribeMessage.Data("thing6", parms[3]));
        } else if (notifyType.getType().equals(NotifyType.AFTERSALE.getType())) {//售后状态通知
            dataList.add(new WxMaSubscribeMessage.Data("thing2", parms[0]));
            dataList.add(new WxMaSubscribeMessage.Data("phrase3", parms[1]));
        }
        return dataList;
    }
}
